package com.wg.core.controller;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.wg.core.thread.fiber.IFiber;
import com.wg.core.thread.fiber.PoolFiber;

/**
 * 控制器基类，实现IController接口的通用方法
 *
 * @author 少爷123
 */
public abstract class BaseController implements IController {
    protected final Log log = LogFactory.get(this.getClass());
    protected final PoolFiber fiber = new PoolFiber();
    protected volatile boolean running = false;
    private final String name;

    public BaseController() {
        this.name = this.getClass().getSimpleName();
    }

    @Override
    public void init() {
        log.info("{} is initializing...", name);
        // 子类可以重写此方法实现自定义初始化
    }

    @Override
    public void start() {
        if (!running) {
            log.info("{} is starting...", name);
            fiber.start();
            running = true;
            log.info("{} started successfully", name);
        } else {
            log.warn("{} is already running", name);
        }
    }

    @Override
    public void shutdown() {
        if (running) {
            log.info("{} is shutting down...", name);
            try {
                fiber.stop();
                running = false;
                log.info("{} shutdown successfully", name);
            } catch (Exception e) {
                log.error("{} shutdown failed", name, e);
            }
        }
    }

    @Override
    public IFiber getFiber() {
        return fiber;
    }

    @Override
    public boolean isRunning() {
        return running;
    }

    @Override
    public String getName() {
        return name;
    }
}
